/**
 * 
 */
package com.nextive.interview.dao.sqlite;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;

import com.nextive.interview.dao.WeightInfoDao;


/**
 * @author Martin
 *
 */
public class SqLiteWeightInfoDao extends SqLiteHelperDao implements WeightInfoDao {

    private static final String DATABASE_NAME = "data";
    private static final String DATABASE_TABLE = "user_weights";
    private static final int DATABASE_VERSION = 2;
    private static final String DATABASE_DROP = "DROP TABLE IF EXISTS " + DATABASE_TABLE;
    private static final String DATABASE_CREATE =
        "create table " + DATABASE_TABLE + " (" + ID_KEY + " integer primary key autoincrement, "
        + WEIGHT_KEY + " real not null, " 
        + DATE_KEY + " text not null);";
	
	public SqLiteWeightInfoDao(Context context) {
		
		super(context);
		
	}
	
	@Override
	public Cursor fetchAllWeighHistoryInfo() {

		return getDatabase().query(DATABASE_TABLE, new String[] {ID_KEY, WEIGHT_KEY, DATE_KEY}, null, 
				null, null, null, null);
		
	}
	
	@Override
	public Cursor fetchWeightHistoryInfo(long id) {
		
		Cursor cursor = getDatabase().query(true, DATABASE_TABLE, new String[] {ID_KEY, WEIGHT_KEY, DATE_KEY}, ID_KEY + "=" 
				+ id, null, null, null, null, null);
		
		if (cursor != null) {
			
			cursor.moveToFirst();
			
		}
		
		return cursor;
		
	}

	@Override
	public boolean deleteWeightInfo(long id) {
		
		return getDatabase().delete(DATABASE_TABLE, ID_KEY + "=" + id, null) > 0;
		
	}

	@Override
	public long createNewWeightInfo(String weight, String date) {
		
		try {

			ContentValues values = new ContentValues();
			values.put(WEIGHT_KEY, weight);
			values.put(DATE_KEY, date);
			
			return getDatabase().insert(DATABASE_TABLE, null, values);

		} finally {
			
			close();
			
		}
		
	}

	@Override
	public boolean updateWeightInfo(long id, String weight, String date) {
		
		try {

			ContentValues values = new ContentValues();
			values.put(WEIGHT_KEY, weight);
			values.put(DATE_KEY, date);
			
			return getDatabase().update(DATABASE_TABLE, values, ID_KEY + "=" + id, null) > 0;

		} finally {
			
			close();
			
		}
	}

	@Override
	protected String getDBName() {
		
		return DATABASE_NAME;
		
	}

	@Override
	protected int getDBVersion() {
		
		return DATABASE_VERSION;
		
	}

	@Override
	protected String getDBCreateStatement() {
		
		return DATABASE_CREATE;
		
	}

	@Override
	protected String getDBDropStatement() {
		
		return DATABASE_DROP;
		
	}
	
}
